package com.swotxu.hhinvoker;

import com.netflix.appinfo.InstanceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaServiceInstance;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Date: 2020/7/4 17:48
 * @Author: swotXu
 */
@RestController
@Configuration
public class HealthController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/health", method = RequestMethod.GET)
    public String health() {
        StringBuilder sb = new StringBuilder();
        // 查询服务列表
        List<ServiceInstance> instanceList = getServiceInstances();
        // 输出服务信息及状态
        for (ServiceInstance service : instanceList) {
            EurekaServiceInstance esi = (EurekaServiceInstance) service;
            InstanceInfo info = esi.getInstanceInfo();

            sb.append(String.format("AppName: %s ---- InstanceId: %s ---- Status: %s </br>"
                    , info.getAppName(), info.getInstanceId(), info.getStatus()));
        }
        return sb.toString();
    }

    @RequestMapping(value = "/metadata", method = RequestMethod.GET)
    public String metadata() {
        StringBuilder sb = new StringBuilder();

        List<ServiceInstance> instanceList = discoveryClient.getInstances("HEALTH-HANDLER-INVOKER");
        for (ServiceInstance service : instanceList) {
            sb.append("developer-name: ").append(service.getMetadata().get("developer-name")).append("</br>");
        }
        return sb.toString();
    }

    /**
     * 查询可以服务
     * @return
     */
    private List<ServiceInstance> getServiceInstances() {
        List<ServiceInstance> result = new ArrayList<>();

        List<String> idList = discoveryClient.getServices();
        for (String id : idList) {
            List<ServiceInstance> instances = discoveryClient.getInstances(id);
            result.addAll(instances);
        }
        return result;
    }
}
